<template>
  <div v-if="currentDevice.devices && currentDevice.devices.length > 0">
    <el-card class="box-card">
      <div slot="header" class="clearfix" style="display:flex;">
        <el-radio-group v-model="ctl_type" size="mini">
          <el-radio-button :label="1">系统轮灌组</el-radio-button>
          <el-radio-button :label="2">临时轮灌组</el-radio-button>
        </el-radio-group>
        <el-button-group class="fr" style="margin-left:auto;">
          <el-button type="primary" icon="el-icon-refresh" size="mini" @click="refresh">刷新状态</el-button>
          <el-button type="primary" icon="el-icon-s-operation" size="mini" :disabled="childSelected.length === 0" @click="showControlAll">控制选中</el-button>
        </el-button-group>
      </div>
      <el-collapse v-model="activeNames">
        <el-collapse-item
          v-for="(item,index) in currentDevice.cells.filter((val) => {
            return +val.ctl_type === +ctl_type
          })"
          :key="index"
          style="padding-bottom:0"
          :name="index"
        >
          <template slot="title">
            <div class="collapse-title flex">
              <b class="mr12">{{ item.name }}</b>
              <el-badge
                v-for="(citem,cindex) in item.devices"
                :key="cindex"
                is-dot
                class="item"
                style="margin:0 1px;"
                :type="getValveClass(citem.rtu_serialno, citem.port)"
              />
              <div class="mlauto pr12">
                <span v-if="getSelectedValves(item) > 0" class="mr12">已选中：<b>{{ getSelectedValves(item) }}</b></span>
                <el-button-group>
                  <el-button type="primary" plain icon="el-icon-check" size="mini" @click.stop="selectAll(item)">全部选中</el-button>
                  <el-button type="default" plain icon="el-icon-close" size="mini" @click.stop="cancelAll(item)">全部取消</el-button>
                </el-button-group>
              </div>
            </div>
          </template>
          <div class="childs-container">
            <dl v-for="(citem,cindex) in item.devices" :key="cindex" class="menux" @click="showControl(citem)">
              <dt><img :src="getDeviceImage(citem,citem.port)" alt="" :style="getDeviceStyle(citem.rtu_serialno)"></dt>
              <dd :class="getValveClass(citem.rtu_serialno,citem.port)">{{ citem.name_raw }}</dd>
              <dd v-if="childSelected.includes(citem)" class="iconfont icon-active" />
            </dl>
          </div>
        </el-collapse-item>
      </el-collapse>
      <el-dialog
        v-el-drag-dialog
        title="阀门控制"
        :append-to-body="true"
        destroy-on-close
        :visible.sync="dialogVisible"
        width="800px"
      >
        <div class="tags">
          <el-tag
            v-for="(item,index) in childSelected"
            :key="index"
            closable
            type="primary"
            style="margin:8px 8px 8px 0;"
            @close="closeTag(index)"
          >
            {{ item.rtu_serialno }}
          </el-tag>
          <div class="h12" />
          <div class="flex">
            <el-checkbox v-model="timeable" border :true-label="1" :false-label="0" style="margin-right:12px;">设置灌溉时长</el-checkbox>
            <el-input v-if="timeable" v-model="timetran" placeholder="灌溉时长" type="number">
              <template slot="append">分钟</template>
            </el-input>
          </div>
        </div>
        <div class="h20" />
        <div>
          <div class="btn-container">
            <el-button type="primary" icon="el-icon-caret-right" @click="control(1)">开阀</el-button>
            <el-button type="danger" :disabled="Boolean(timeable)" icon="el-icon-switch-button" @click="control(0)">关阀</el-button>
          </div>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { sendCommand } from '@/api/device'
import { uniqueArr } from '@/utils'
import { getDeviceImage, getDeviceStatus, formatPlanDataForValvesNew } from '@/utils/device'
import { dclassCodeMap } from '@/utils/constant'
import { addOne } from '@/api/plan'
export default {
  data() {
    return {
      activeName: 'first',
      controlMode: true,
      activeNames: [0],
      dialogVisible: false,
      childSelected: [],
      ctl_type: 1,
      timeable: 0,
      timetran: 10,
      Open1: 0,
      Open2: 0
    }
  },
  computed: {
    ...mapGetters(['currentDevice', 'devicesObj', 'uid'])
  },
  methods: {
    showPlan() {
      this.dialogTimeVisible = true
    },
    showControl(item) {
      if (!this.childSelected.includes(item)) {
        this.childSelected.push(item)
      } else {
        this.childSelected.splice(this.childSelected.findIndex((val) => {
          return val === item
        }), 1)
      }
      this.childSelected = uniqueArr(this.childSelected)
    },
    showControlAll() {
      this.dialogVisible = true
    },
    closeTag(index) {
      this.childSelected.splice(index, 1)
    },
    selectAll(cell) {
      this.childSelected = uniqueArr(this.childSelected.concat(cell.devices))
    },
    cancelAll(cell) {
      this.childSelected = this.childSelected.filter(val => {
        return !cell.devices.includes(val)
      })
    },
    control(value) {
      if (!this.timeable) {
        this.$confirm('确定要进行此操作吗？', '操作确认', { type: 'warning' }).then(() => {
          for (const nozzle of this.childSelected) {
            const serialno = nozzle.rtu_serialno
            const namekey = value ? `CH${nozzle.port}_OPEN` : `CH${nozzle.port}_CLOSE`
            const action = {
              namekey: namekey,
              value
            }

            sendCommand(action, serialno).then(res => {
              this.$message({ message: res.msg, type: 'success', showClose: true })
            })
          }
        })
      } else {
        const info = {
          serialno: this.currentDevice.serialno,
          val: this.timetran,
          delaySec: 30,
          valves: this.childSelected
        }
        const submitData = formatPlanDataForValvesNew(info, this.uid)
        this.addOne(submitData)
      }
    },
    async addOne(formData) {
      const { msg } = addOne(formData)
      this.$message({ message: msg || '操作成功', type: 'success', showClose: true })
    },
    async refresh() {
      await this.$store.dispatch('device/getAll')
    },
    getDeviceImage(currentDevice, port) {
      if (this.devicesObj[currentDevice.rtu_serialno]) {
        return getDeviceImage(this.devicesObj[currentDevice.rtu_serialno], port)
      }
      return ''
    },
    getValveClass(rtu_serialno, port) {
      const res = getDeviceStatus(this.devicesObj[rtu_serialno])
      if (+res[port - 1] === 1) {
        return 'success'
      }
      return 'info'
    },
    getDeviceStyle(rtu_serialno) {
      const device = this.devicesObj[rtu_serialno]
      if (+device.product_type === +dclassCodeMap.qf) {
        const A = (device.states && device.states.A) || 90
        const degree = Math.round(A / 100)
        return {
          transform: `rotate(${degree - 90}deg)`,
          transition: 'transform 0.5s ease' // 可选的过渡效果
        }
      }
    },
    getSelectedValves(item) {
      return item.devices.filter((val) => {
        return this.childSelected.includes(val)
      }).length
    }
  }
}
</script>

<style lang="scss" scoped>
.collapse-title{
  width:100%;
  align-items:center;
  b{
    min-width:48px;
  }
}
</style>
